package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmNewsDTO;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import io.jsonwebtoken.lang.Collections;
import io.seata.common.util.CollectionUtils;
import io.seata.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    WmNewsMapper wmNewsMapper;
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //检查参数
        dto.checkParam();
        //记录当前页
        Integer currentPage = dto.getPage();
        //设置起始页
        dto.setPage((currentPage-1)*dto.getSize());
        //判断传输过来的标题是否为空
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        //分页查询
        List<WmNewsVO> wmNewsVOList = wmNewsMapper.findListAndPage(dto);
        //统计一共有多少条数据
        long cotunt = wmNewsMapper.findListCount(dto);
        //结果返回
        PageResponseResult result = new PageResponseResult(currentPage, dto.getSize(), cotunt, wmNewsVOList);
        return result;
    }

    /**
     * 查询所有自媒体文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //参数检查
        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数有误，参数不能为空");
        }
        dto.checkParam();
        //查询条件封装条件封装
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //文章标题模糊查询
        queryWrapper.like(StringUtils.isNotBlank(dto.getKeyword()),WmNews::getTitle,dto.getKeyword());
        //频道id查询
        queryWrapper.eq(dto.getChannelId()!=null,WmNews::getChannelId,dto.getChannelId());
        //文章状态查询
        queryWrapper.eq(dto.getStatus()!=null,WmNews::getStatus,dto.getStatus());
        //发布时间区间查询
        queryWrapper.between(dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null,
                WmNews::getPublishTime,
                dto.getBeginPubDate(),
                dto.getEndPubDate());
        //当前自媒体人文章
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"未检测到当前登陆用户，请登陆后重试");
        }
        queryWrapper.eq(WmNews::getUserId,user.getId());
        //按照创建时间降序排序
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        //构建分页查询对象
        Page<WmNews> pageReq = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmNews> pageresult = this.page(pageReq, queryWrapper);
        //返回封装结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageresult.getTotal(), pageresult.getRecords());
        result.setHost(webSite);
        return result;
    }


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //1.参数校验
        if (StringUtils.isBlank(dto.getContent())|| StringUtils.isBlank(dto.getTitle())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"标题或者内容不能为空");
        }
        //校验用户是否登陆
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"未检测到用户登陆，请登陆后重试");
        }
        //2.保存或修改文章
        WmNews wmNews = new WmNews();
        //将dto中的值设置到对象中
        BeanUtils.copyProperties(dto,wmNews);
        //如果文章布局时自动的，也就是说值为-1，我们将其设置为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        //处理dto参数，images封面集合  转换成  字符串
        String images = imageListToStr(dto.getImages());
        wmNews.setUserId(user.getId());
        wmNews.setImages(images);
        saveWmNews(wmNews);
        //如果时草稿，直接返回
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())) {
            return ResponseResult.okResult();
        }
        //3.1抽取文章中关联图片的路径
        List<String> materials = parseContentImages(dto.getContent());
        //3.2 关联文章中的图片和素材关系
        if (!CollectionUtils.isEmpty(materials)) {
            saveRelativeInfo(materials,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        }
        //3.3 关联文章封面中的图片和素材关系  封面可能是选择自动或者是无图
        saveRelativeInfoForCover(dto,materials, wmNews);

        //3.4 TODO:发送待审核消息
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送，待审核消息==> 队列：{}，文章id：{}",NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());

        return ResponseResult.okResult();
    }


    /**
     *  关联文章封面中的图片和素材关系
     * @param dto 前端用户选择的用户信息
     * @param materials 内容中解析的图片列表
     * @param wmNews 文章id
     */
    private void saveRelativeInfoForCover(WmNewsDTO dto, List<String> materials, WmNews wmNews) {
        //前端选择的图
        List<String> images = dto.getImages();
        //自动获取封面
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            int materialSize = materials.size();
            //单图
            if (materialSize>0&&materialSize<=2) {
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                //多图
            } else if (materialSize > 2) {
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                //无图
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            updateById(wmNews);
        }
        //保存图片列表和素材的关系
        if (images!=null&&images.size()>0) {
            images = images.stream().map(url->url.replaceAll(webSite,""))
                    .collect(Collectors.toList());
            saveRelativeInfo(images, wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);

        }

    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    /**
     *  保存素材和文章关系
     * @param urls 文章中的图片素材list集合
     * @param newsId 文章id
     * @param type 类型：0；0素材内容；1封面内容
     */
    private void saveRelativeInfo(List<String> urls, Integer newsId, Short type) {
        //查询文章中内容对应素材的ID
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(urls, WmThreadLocalUtils.getUser().getId());
        //判断素材是否缺失
        if (CollectionUtils.isEmpty(ids)||ids.size()<urls.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"相关素材缺失，保存失败！！！");
        }
        //保存关系
        wmNewsMaterialMapper.saveRelations(ids,newsId,type);
    }

    /**
     *  抽取文章内容中  所有引用的图片
     * @param content 文章内容
     * @return 返回一个url的String，List集合
     */
    private List<String> parseContentImages(String content) {
        List<Map> list = JSON.parseArray(content, Map.class);
        //遍历文章内容 将所有的type为image的  value获取出来，去除前缀路径
        return list.stream()
                //过滤出type=image的所有数据
                .filter(map -> map.get("type").equals("image"))
                //获取到image下的value路径
                .map(map -> String.valueOf(map.get("value")))
                //图片去除url前缀
                .map(url -> url.replaceAll(webSite, ""))
                //去除重复的路径
                .distinct()
                //stream 转成list集合
                .collect(Collectors.toList());
    }

    /**
     *  将图片list集合转换为规定格式的字符串
     */
    private String imageListToStr(List<String> images) {
        if (Collections.isEmpty(images)) {
            return null;
        }
        return images.stream().map(url -> url.replaceAll(webSite, ""))
                .collect(Collectors.joining(","));
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 保存或修改文章
     */
    private void saveWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP); //上架
        if (wmNews.getId()==null) { //如果文章不存在则保存
            save(wmNews);
        }else { //如果文章存在则修改
            //删除当前文章和 素材关系表的数据
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }
        //5. 通知定时发布文章
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
    }



    /**
     * 根据文章id查询文章
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //参数校验
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"未查询到该文章，请刷新后重试");
        }
        //执行查询
        WmNews wmNews = getById(id);
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章数据不存在，请刷新后重试");
        }
        //返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);


        return result;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //参数检查
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章信查询不到，请刷新后重试");
        }
        //获取数据
        WmNews wmNews = getById(id);
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章数据不存在，请刷新后重试");
        }
        //判断当前文章的状态  status=9  enable=1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.删除中间表和，文章和图片的关联关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if(enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable))){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                .set(WmNews::getEnable,dto.getEnable()));
        if (wmNews.getArticleId()!=null) {
            if(enable.equals(WemediaConstants.WM_NEWS_UP)){
                // 上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            }else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    WmUserMapper wmUserMapper;
    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //参数校验
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到该文章数据，可能被删除，请刷新后重试");
        }
        //根据id查询wmNews对象
        WmNews wmNews = getById(id);
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到该文章数据，可能被删除，请刷新后重试");
        }
        //根据作者id查询作者名字,判断用户id是否为空
        WmUser wmUser =null;
        if (wmNews.getUserId()!=null) {
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //封装返回结果
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVO);
        if (wmUser!=null) {
            wmNewsVO.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVO);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 文章审核成功或者失败
     * @param dto
     * @return
     */
    public ResponseResult updateStatus(NewsAuthDTO dto) {
        //参数检查
        if (dto==null||dto.getId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"文章id为空，请刷新后从新提交");
        }
        //通过id查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"违章数据不存在，请刷新后重试");
        }
        //检查文章状态，不能为9，9是已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已经发布，无需再次审核");
        }

        //修改文章状态
        wmNews.setStatus(dto.getStatus());
        //如果消息不为空，则设置原因消息
        if (Strings.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        //5. 通知定时发布文章
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
